<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
class Comment_model extends MY_Model {
	var $table = 'comment';

	public function __construct() {
		parent::__construct ();
	}
	
	public function addComment($data) {
		$where = array(
			'order_id' => $data['order_id'],
			'user_id' => $data['user_id']
		);
		$tmp1 = $this->get_num($where);
		$tmp2 = $this->db->select('address_id')->from('order')->where(array('id'=>$data['order_id'], 'user_id'=>$data['user_id'], 'status'=>  REST_Controller::PAY_STATUS_FINISH))->get()->row_array();
		if(!$tmp2 || $tmp1 > 0) {
			return false;
		}
		$data['address_id'] = $tmp2['address_id'];
		$result = $this->insert($data);
		return $result;
	}
	
	public function comment($orderId, $uid, $config=array()) {
		$limit = NULL;
		$offset = NULL;		
		if (!empty($config)) {
			foreach ($config as $key => $val) {
				$$key = $val;
			}
		}
		$sql = $this->db->select('address_id')->from($this->table)->where(array('order_id'=>$orderId, 'user_id'=>$uid))->get_compiled_select();
		if ($limit && $offset >= 0) {
			$this->db->limit($limit, $offset);
		}
		$query = $this->db->select('u.id,u.username,round((c.product_score + c.schedule_score + c.service_score) / 3) as score,c.content,c.created_at')
				->from($this->table . ' c')
				->join('user u', 'c.user_id=u.id', 'left')
				->where("c.address_id in ($sql)")
				->get();
		return $query->result_array();
	}
}